package sheetOperations;

import java.util.HashMap;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;

public class SheetCopyTools {
	
	/**
	 * Helper function to add a row into a workbook at the last position
	 * @param row Row to be copied
	 * @param wkb Target workbook
	 * @param styleMap A hashmap containing CNEE, mapped to a hashmap containing cell style index mapped to a cellstyle
	 */
	public static void addRow(Row row, HSSFSheet wks,boolean title, HashMap<String,HashMap<Short,CellStyle>> styleMap){
		
		//If row is null terminate copy
		if(row!=null){
			//create a new row in workbook at the end
			Row newRow = null;
			if(title)
				newRow = wks.createRow(wks.getLastRowNum());
			else
				newRow = wks.createRow(wks.getLastRowNum()+1);
			int counter =0;
			String cnee = wks.getSheetName();
			
			counter = row.getLastCellNum();
			
			for(int i=0;i<counter;i++){
				Cell curr = row.getCell(i);
				if(curr!=null){
					Cell newCell = null;
					int type = curr.getCellType();

					switch(type){
						case Cell.CELL_TYPE_BLANK:
							newCell = newRow.createCell(i);
							newCell.setCellType(type);
							break;
						case Cell.CELL_TYPE_NUMERIC:
							newCell = newRow.createCell(i);
							newCell.setCellType(type);
							newCell.setCellValue(curr.getNumericCellValue());
							break;
						case Cell.CELL_TYPE_STRING:
							newCell = newRow.createCell(i);
							newCell.setCellType(type);
							newCell.setCellValue(curr.getStringCellValue());
							break;
					}
					if(styleMap.get(cnee)==null){
						styleMap.put(cnee, new HashMap<Short, CellStyle>());
					}
					if(styleMap.get(cnee).get(curr.getCellStyle().getIndex())==null){
						CellStyle cs = wks.getWorkbook().createCellStyle();
						cs.cloneStyleFrom(curr.getCellStyle());
						styleMap.get(cnee).put(curr.getCellStyle().getIndex(), cs);
					}
					newCell.setCellStyle(styleMap.get(cnee).get(curr.getCellStyle().getIndex()));
				}
			}
		}
	}
}
